package cn.sunline.rest;

import cn.sunline.rest.handler.HttpRouterInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NidaServer {
    
    private int port;
    
    private Channel ch;
    
    private ServerBootstrap b;
    
    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;
    
    public NidaServer(int port) {
        this.port = port;
    }

    public void run() {
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();
        try {
            b = new ServerBootstrap();
            b.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new HttpRouterInitializer());
            b.option(ChannelOption.SO_BACKLOG, 128);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            ch = b.bind(port).sync().channel();//
            ch.closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public void stop() {
        if ( ch != null ) {
            ch.close();
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
